<template>
  <div>
    <el-dialog :visible="showAssign" title="分配权限" @close="cancelBtn">
      <el-tree
        v-loading="loading"
        :data="allPermission"
        show-checkbox
        check-strictly
        :props="defaultProps"
        :default-expand-all="true"
        :default-checked-keys="selectPermission"
        node-key="id"
        @check-change="change"
      ></el-tree>
      <div>
        <el-button type="primary" @click="btnOk">确定</el-button>
        <el-button @click="cancelBtn">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionList } from "@/api/permission";
import { getRoleDetail, assignPerm } from "@/api/setting";
import { formatDeparts } from "@/utils/formatTree";
export default {
  name: "treeAssign",
  props: ["showAssign"],
  data() {
    return {
      loading: false,
      allPermission: [],
      selectPermission: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
      update: {
        id: "",
        permIds: [],
      },
    };
  },
  methods: {
    cancelBtn() {
      this.$emit("update:showAssign", false);
      this.allPermission = [];
      this.selectPermission = [];
      this.update.id = "";
      this.update.permIds = [];
    },
    // 获取用户已有的权限,以及所有权限
    async getPermission(id) {
      this.loading = true;
      let result = await getPermissionList();
      let result2 = await getRoleDetail(id);

      this.allPermission = formatDeparts(result, "0");
      console.log("allper", this.allPermission);
      console.log("result2", result2);
      this.selectPermission = result2.permIds;
      this.update.id = id;
      this.update.permIds = result2.permIds;
      this.loading = false;
    },
    change(node, select, sonSelect) {
      if (select) {
        this.update.permIds.push(node.id);
        console.log(this.update, "up");
      } else {
        this.update.permIds = this.update.permIds.filter(
          (item) => item != node.id
        );
        console.log(this.update, "pop");
      }
    },
    async btnOk() {
      try {
        await assignPerm(this.update);
        this.$message({
          type: "success",
          message: "分配权限成功",
        });
      } catch (error) {
        this.$message({
          type: "info",
          message: "分配权限失败",
        });
      }
      this.cancelBtn();
    },
  },
};
</script>

<style>
</style>